<template>
	<view class="home">
		<view class="text">
			电动伸缩杆
		</view>
		<!-- 		<u-button @click="senDing1" text="按钮" size="normal" color="rgb(10, 185, 156)"></u-button>
		<view class="" style="height: 50rpx;">
			
		</view>
		<u-button @click="senDing2" text="按钮" size="normal" color="rgb(185, 40, 26)"></u-button> -->
		<view class="dipf">
			<!-- 慢 -->
			<view class="top">
				<view class="up" @click="manshangFn">
					<view class="yuan" hover-class="avcyuan">
						<view class="triangle" hover-class="avtriangle">

						</view>
					</view>
				</view>
				<view class="down" @click="manxiaFn">
					<view class="yuan" hover-class="avcyuan">
						<view class="triangle" hover-class="avtriangle">

						</view>
					</view>
				</view>
				<view class="tex">
					<view class="tritex">
						点动
					</view>
				</view>
			</view>
			<!-- 快 -->
			<view class="top">
				<view class="up" @click="kuaishangFn">
					<view class="yuan" hover-class="avcyuan">
						<view class="triangle" hover-class="avtriangle">

						</view>
					</view>
				</view>
				<view class="down" @click="kuaixiaFn">
					<view class="yuan" hover-class="avcyuan">
						<view class="triangle" hover-class="avtriangle">

						</view>
					</view>
				</view>
				<view class="tex">
					<view class="tritex">
						连动
					</view>
				</view>
			</view>
		</view>
		<!-- 自动 -->
		<view class="zidong" hover-class="avczidong" @click="zidongFn">
			自动伸缩
		</view>
		<view class="zidong" hover-class="avczidong" @click="zantingFn">
			取消自动
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {

				deviceId: '',
				serviceId: '',
				characteristics: [],
				characteristicId: '',
				manxia: ['0xFF', '0x10', '0x00', '0x03', '0x00', '0x02', '0x04', '0x00', '0x04', '0x00', '0x14', '0xC5',
					'0x9F'
				],
				manshang: ['0xFF', '0x10', '0x00', '0x08', '0x00', '0x02', '0x04', '0x00', '0x04', '0x00', '0x14', '0x84',
					'0x2C'
				],
				kuaixia: ['0xFF', '0x10', '0x00', '0x03', '0x00', '0x02', '0x04', '0x00', '0x04', '0x01', '0x2C', '0xC5',
					'0xDD'
				],
				kuaishang: ['0xFF', '0x10', '0x00', '0x08', '0x00', '0x02', '0x04', '0x00', '0x04', '0x01', '0x2C', '0x84',
					'0x6E'
				],
				timerSc: null,
			}
		},
		destroyed() {
			clearInterval(this.timerSc)
			console.log('销毁',this.timerSc);
		},
		onLoad(option) {
			this.deviceId = this.vuex_deviceId
			this.getBLEDeviceServices()
			uni.showLoading({
				title: '开启服务中...'
			});
			setTimeout(() => {
				uni.hideLoading()
			}, 10000)
		},
		onShow() {
			// this.getBLEDeviceServices()
		},
		methods: {
			// 慢
			manshangFn() {
				let counmap = this.manshang
				const buffer = new ArrayBuffer(counmap.length)
				const dataView = new DataView(buffer)
				for (var i = 0; i < counmap.length; i++) {
					dataView.setUint8(i, counmap[i])
				}
				this.sendMsgToKey(buffer)
				console.log('慢上');
			},
			manxiaFn() {
				let counmap = this.manxia
				const buffer = new ArrayBuffer(counmap.length)
				const dataView = new DataView(buffer)
				for (var i = 0; i < counmap.length; i++) {
					dataView.setUint8(i, counmap[i])
				}
				this.sendMsgToKey(buffer)
				console.log('慢下');
			},
			kuaishangFn() {
				let counmap = this.kuaishang
				const buffer = new ArrayBuffer(counmap.length)
				const dataView = new DataView(buffer)
				for (var i = 0; i < counmap.length; i++) {
					dataView.setUint8(i, counmap[i])
				}
				this.sendMsgToKey(buffer)
				console.log('快上');
			},
			kuaixiaFn() {
				let counmap = this.kuaixia
				const buffer = new ArrayBuffer(counmap.length)
				const dataView = new DataView(buffer)
				for (var i = 0; i < counmap.length; i++) {
					dataView.setUint8(i, counmap[i])
				}
				this.sendMsgToKey(buffer)
				console.log('快下');
			},
			zidongFn() {
				this.zantingFn()
				let nub = 0
				this.timerSc = setInterval(() => {
					if (nub < 20) {
						nub++
						this.manxiaFn()
						
						console.log('升起', nub);
					} else if (nub >= 5) {
						nub++
						if (nub >= 40) {
							nub = 0
						}
						this.manshangFn()
						console.log('下降', nub);
					}

				}, 1000)
				console.log('自动');
			},
			zantingFn() {
				clearInterval(this.timerSc)
				console.log('暂停');
			},
			// 传输数据
			senDing1() {

			},
			senDing2() {

				console.log('off', buffer);
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.vuex_deviceId,
						success: (res) => {
							//E95D93AF-251D-470A-A062-FA1922DFA9A8
							//6E400001-B5A3-F393-E0A9-E50E24DCCA9E
							res.services.forEach((item) => {

								if (item.uuid.indexOf("0000FFF0") != -1) {
									this.serviceId = item.uuid;

									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("0000FFE0") != -1) {
									this.serviceId = item.uuid;

									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								// if (item.uuid.indexOf("0000FFF0") != -1) {
								// 	this.serviceId = item.uuid;

								// 	//获取特征
								// 	this.getBLEDeviceCharacteristics()
								// }
								// if (item.uuid.indexOf("470A") != -1) {
								// 	this.serviceId = item.uuid;

								// 	//获取特征
								// 	this.getBLEDeviceCharacteristics()
								// }
							})
						}
					})
				}, 1500)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: (res) => {

							this.characteristics = res.characteristics
							res.characteristics.forEach((item) => {

								if (item.uuid.indexOf("FFF2") != -1) {
									this.fff = item.uuid

								}
								if (item.uuid.indexOf("FFE1") != -1) {
									this.fff = item.uuid

								}
								if (item.uuid.indexOf("0000FFE1") != -1) {

									this.characteristicId = item.uuid
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								if (item.uuid.indexOf("0000FFF1") != -1) {

									this.characteristicId = item.uuid


									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(characteristicId) {
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceId,

					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.characteristicId,
					success: (res) => {
						// vuex

						// uni.$u.vuex('vuex_devicename', this.vuexlist.name)
						uni.hideLoading()
						this.listenValueChange()
						uni.showToast({
							title: '服务已开启',
							icon: 'success',
							mask: true,
							duration: 1000
						});
					},
					fail: (res) => {
						uni.hideLoading()
						uni.showToast({
							title: '获取服务失败',
							icon: 'fail',
							mask: true,
							duration: 2000
						});

					}
				})

			},
			// 分包
			/**
			 * 向设备发送消息(分包发送，单包20字节，递归发送)
			 */
			sendMsgToKey(buffer) {
				var that = this //vue中的this
				const packageSize = 20 //分包大小
				if (buffer.byteLength <= 20) { //如果小于20直接发送，不再继续调用
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: buffer,
						writeType: 'write',
						success: (res) => {
							//此时设备已接收到你写入的数据
							setTimeout(() => {
								if (this.fanti) {
									this.modifyup()
								}
							}, 500)

						},
						fail: (err) => {
							if (err.errCode == 10006) {
								uni.hideLoading()
								uni.showToast({
									title: '当前连接已断开',
									icon: 'success',
									mask: true,
									duration: 2000
								});
							}
							if (err.errCode == 10004) {
								uni.hideLoading()
								uni.showToast({
									title: '未找到服务',
									icon: 'success',
									mask: true,
									duration: 2000
								});
							}
							if (err.errCode == 10005) {
								uni.hideLoading()
								uni.showToast({
									title: '未找到特征值',
									icon: 'success',
									mask: true,
									duration: 2000
								});
							}
						},
						complete: function() {}
					})
				} else { //如果大于20发送完成后继续递归调用
					var newData = buffer.slice(20)
					var writeBuffer = buffer.slice(0, 20)
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: writeBuffer,
						writeType: 'write',
						success: function(res) {
							//写入成功后继续递归调用发送剩下的数据
							that.sendMsgToKey(newData)
						},
						fail: (err) => {
							if (err.errCode == 10006) {
								uni.hideLoading()
								uni.showToast({
									title: '当前连接已断开',
									icon: 'success',
									mask: true,
									duration: 2000
								});
							}
							if (err.errCode == 10004) {
								uni.hideLoading()
								uni.showToast({
									title: '未找到服务',
									icon: 'success',
									mask: true,
									duration: 2000
								});
							}
							if (err.errCode == 10005) {
								uni.hideLoading()
								uni.showToast({
									title: '未找到特征值',
									icon: 'success',
									mask: true,
									duration: 2000
								});
							}
						},
						complete: function() {}
					})
				}

			},
			// 【9】监听消息变化
			listenValueChange() {
				setTimeout(() => {
					uni.onBLECharacteristicValueChange(res => {
						let resHex = this.ab2hex(res.value)
						console.log('res', res, resHex);
						this.receive(resHex)
					})
				}, 300)

			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			receive(data) {
				console.log('返回', data);
			},
		}
	}
</script>
<style scoped lang="scss">
	.home {
		// height: 90vh;
		text-align: center;

		.text {
			padding: 30rpx;
			border-radius: 20rpx;
			background-color: #424950;
			margin: 30rpx auto;
			margin-bottom: 50rpx;
			color: #fbd8af;
			font-size: 50rpx;
			width: 500rpx;
			text-align: justify;
			text-align-last: justify;
		}

		.dipf {
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding: 0 30rpx;

			.top {
				height: 650rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: space-between;
				padding: 50rpx;
				border-radius: 50rpx;
				background-color: #4c525f;

				.up {
					width: 200rpx;
					height: 200rpx;
					border-radius: 200rpx;
					border: 3rpx solid #fcf7f3;
					display: flex;
					justify-content: center;
					align-items: center;

					.yuan {
						width: 120rpx;
						height: 120rpx;
						border-radius: 200rpx;
						background-color: #282830;
						border: 5rpx solid #343841;
						box-shadow: 0rpx 0rpx 20rpx #1c1f22;
						display: flex;
						justify-content: center;
						align-items: center;

						.triangle {
							margin-top: -10rpx;
							width: 0;
							height: 0;
							border-bottom: 30rpx solid #fbd8af;
							border-right: 30rpx solid transparent;
							border-left: 30rpx solid transparent;
						}
					}

					.avcyuan {
						background-color: #fbd8af;
					}

				}

				.down {
					width: 200rpx;
					height: 200rpx;
					margin-top: 50rpx;
					border-radius: 200rpx;
					border: 3rpx solid #fcf7f3;
					display: flex;
					justify-content: center;
					align-items: center;

					.yuan {
						width: 120rpx;
						height: 120rpx;
						border-radius: 200rpx;
						background-color: #282830;
						border: 5rpx solid #343841;
						box-shadow: 0rpx 0rpx 20rpx #1c1f22;
						display: flex;
						align-items: center;
						justify-content: center;

						.triangle {
							margin-top: 10rpx;
							width: 0;
							height: 0;
							border-top: 30rpx solid #fbd8af;
							border-right: 30rpx solid transparent;
							border-left: 30rpx solid transparent;
						}

					}

					.avcyuan {
						background-color: #fbd8af;
					}

				}

				.tex {
					width: 120rpx;
					height: 120rpx;
					border-radius: 200rpx;
					background-color: #282830;
					border: 5rpx solid #343841;
					box-shadow: 0rpx 0rpx 20rpx #1c1f22;
					display: flex;
					align-items: center;
					justify-content: center;
					color: #fbd8af;
					font-size: 40rpx;
				}
			}
		}

		.zidong {
			width: 500rpx;
			border-radius: 100rpx;
			padding: 30rpx;
			font-size: 60rpx;
			margin: 30rpx auto;
			color: #fbd8af;
			background-color: #4c525f;
		}

		.avczidong {
			background-color: #687283;
		}
	}
</style>
<style>
	page {
		background-color: #272a31;
	}
</style>